#include "HX710C.h"
#include "Aip33624.h"
#include "key.h"
#include "WaterPump.h"
#include "flash.h"
#include "LED.h"
#include "RTC.h"

static float Init_val = 0;      //记录要校准的值
static float Not_weight = 0;       //记录初始
static float Current_Water_weight = 0;
float K_Weight;
float B_Weight;

void HX710C_Init(void)
{
		GPIO_Config_T gpioConfig;
    RCM_EnableAHBPeriphClock(RCM_AHB_PERIPH_GPIOB);
		
    gpioConfig.pin = HX710_PIN_CLK;
    gpioConfig.mode = GPIO_MODE_OUT;
    gpioConfig.outtype = GPIO_OUT_TYPE_PP;
    gpioConfig.speed = GPIO_SPEED_50MHz;
    gpioConfig.pupd = GPIO_PUPD_NO;
    GPIO_Config(HX710_GPIO_CLK, &gpioConfig);
	
		gpioConfig.pin = HX710_PIN_DIO;
    gpioConfig.mode = GPIO_MODE_IN;
		gpioConfig.pupd =GPIO_PUPD_PU;
    GPIO_Config(HX710_GPIO_DIO, &gpioConfig);
	
}

unsigned long HX710C_Read(void)    /******************获取称重值*****************/
{
	unsigned long count;
	u8 i;
	HX710_CLK_0;
	count = 0;	
	while(HX710_DIO);
	for(i=0;i<24;i++)
	{
		HX710_CLK_1;
		count = count << 1;
		HX710_CLK_0;	
		if(HX710_DIO)
		count++;	
	}
	HX710_CLK_1;
	count = count^0x800000;
	HX710_CLK_0;	
	return (count/128);
}


float Read_Weight(void)        /*****************冒泡排序*****************/
{
	u8 i,j,k;
static float Weight_Buff[7];
	float temp,num=0;
	for(i=0;i<7;i++)
	{
		Weight_Buff[i]= HX710C_Read();
	}
	for(j=0;j<7-1;j++)
	{
		for(k=1;k<7-j;k++)
		{
			if(Weight_Buff[k-1]>Weight_Buff[k])
			{
				temp = Weight_Buff[k-1];
				Weight_Buff[k-1]=Weight_Buff[k];
				Weight_Buff[k]=temp;
			}
		}
	}
		for(i=0;i<5;i++)
		{
			num+=Weight_Buff[i+1];	//去掉最大值跟最小值
		}
	return (num/5);
}



u8 Cali_demand = 0;

u8 Calc_flag = _Cali_Null;
void Calc_flash(void)
{
	
	switch(Calc_flag)
	{
		case _Cali_start:
			 mcu_dp_enum_update(DPID_APP_CALI,_Cali_no_water); //枚举型数据上报;
		break;
		case _Cali_no_water:                //提醒用户倒水空桶
		break;
		case _Cali_no_water_finish:           //倒水完成                    //2
			  Weight_calibration(0); 
				B_Weight =  Not_weight; 		//得到b的值
				mcu_dp_enum_update(DPID_APP_CALI,_Cali_full_water); //枚举型数据上报;
				Calc_flag = _Cali_full_water;
		break;
		case _Cali_full_water:             //加水
		break;
		case _Cali_full_water_finish:      //加水完成                //4
				Weight_calibration(1);                                 //A
				K_Weight = (Init_val - B_Weight)/2000;
				Weight_flash_Save((u32)Get_Weight(),K_Weight);     //把x，k ,存了进去
				mcu_dp_bool_update(DPID_CALI_STATUS,1); //BOOL型数据上报;
				Calc_flag = _Cali_Null;
		break;
		default:
		break;
	}
	if(HALL_flag == 1 && pump_stop_flag ==0)
	{
		LED_Water_Wight(Led_Weight_Check());//显示灯的数量
	}
	else
	{
		Red_Blink();               //红灯呼吸出现故障
	}
//	printf("Read_Weight=%d \r\n",(u32)Read_Weight());
//	printf("%d\r\n",Led_Weight_Check());
//	printf("Not_weight=%d \r\n",(u32)Not_weight);
//	printf("Init_val =%d \r\n",(u32)Init_val);
//	printf("B_Weight=%d \r\n",(u32)B_Weight);
//	printf("K_Weight =%f \r\n",K_Weight);

}


u8 Write_flag = 0;
///////////////////***********存储水量X跟K*********************////////////////
void Write_K_B_clac(void)
{         
	if(Write_flag == 1)
	{
		Write_flag = 0;
		Weight_flash_Save((u32)Get_Weight(),K_Weight);     //把x，k ,存了进去
		

	}
}



void Read_B_K_Cali(void)       //从flash中读取K跟水量
{
	K_Weight = ReadFlash(User_Data+4);                         //k
	B_Weight = (Read_Weight()-(ReadFlashTest(User_Data)*K_Weight));   //B
	Init_val = ((2000*K_Weight)+B_Weight);	
	filter_time = ReadFlashTest(User_Data+8);
	Pure_time = ReadFlashTest(User_Data+12);
	Clear_time_report= ReadFlashTest(User_Data+16);
}




float Get_Weight(void) //测得实际的重量
{
	float Curr_vall = 0;            
	Curr_vall = (float)HX710C_Read();
	if(Curr_vall<B_Weight)
	{
		Curr_vall = B_Weight;
	}
	if(Curr_vall>Init_val)
	{
		Curr_vall = Init_val;
	}
	
	return ((Curr_vall - B_Weight)/K_Weight);
}



void Weight_calibration(u8 cal)  //开始校准		函数需调用两次
{
	Aip33624_WriteData(0xc0,0x00);	 
	if(cal == 1)	
    Init_val = Read_Weight();               //获取带重物的  A
	else 
 	  Not_weight = Read_Weight();             //获取不带重物 B
}

	


void Weight_flash_Save(u32 user_data,float K_data)
{
	EarseFlash_1K(User_Data);//擦除数据
	WriteFlash(User_Data,(uint8_t *)&user_data,4);//写入掉电前的水量
	WriteFlash(User_Data+4,(uint8_t *)&K_data,4);//写入K
	WriteFlash(User_Data+8,(uint8_t *)&filter_time,4);//写入
	WriteFlash(User_Data+12,(uint8_t *)&Pure_time,4);//写入
	WriteFlash(User_Data+16,(uint8_t *)&Clear_time_report,4);//写入
}
	


void again_flash_Save(u32 user_data,float K_data)
{
	filter_time=30;
	Pure_time=30;
	Clear_time_report=30;
	EarseFlash_1K(User_Data);//擦除数据
	WriteFlash(User_Data,(uint8_t *)&user_data,4);//写入掉电前的水量
	WriteFlash(User_Data+4,(uint8_t *)&K_data,4);//写入K
	WriteFlash(User_Data+8,(uint8_t *)&filter_time,4);//写入
	WriteFlash(User_Data+12,(uint8_t *)&Pure_time,4);//写入
	WriteFlash(User_Data+16,(uint8_t *)&Clear_time_report,4);//写入
}
	













u8 Led_Weight_Check(void)
{
	static	u16 LED_Weight = 0;     //用来计算要亮的灯的数量
			if(Get_Weight()>1900)     
			{
				LED_Weight = 10;
			}
			else if(Get_Weight()<200 && Get_Weight()>100)
			{
				LED_Weight = 1;
			}
			else if(Get_Weight()<400 && Get_Weight()>300)
			{
				LED_Weight = 2;
			}
			else
			{
				LED_Weight = (int)(Get_Weight()/200);
			}
	return LED_Weight;
}


/*****************上报饮水量*********************/
//需要定时一下
void Judge_drink_weight(void)
{
	
	if((Current_Water_weight - Get_Weight()) >=20)
	{
		drink_time_report();              //饮水时间上报
		mcu_dp_value_update(DPID_WATER_QUANTITY,(Current_Water_weight - Get_Weight()));        //VALUE型数据上报饮水量
		Current_Water_weight = Get_Weight();           
	}
	else
	{
		Current_Water_weight = Get_Weight();           //存上一次饮水量
	}
	
}



//char Timer[6] = {0};
void drink_time_report(void)
{
	static	u8 Timer[6] = {0};
	static char data_char[15] = {'0'};
		RTC_TIME_T TimeStruct ;
		RTC_DATE_T DateStruct;
		RTC_ReadTime(RTC_FORMAT_BIN, &TimeStruct);
		RTC_ReadDate(RTC_FORMAT_BIN, &DateStruct);
	
			Timer[4]=TimeStruct.minutes;	
			Timer[5]= TimeStruct.seconds;	
			Timer[0]=DateStruct.year;		
			Timer[1]=DateStruct.month;		
			Timer[2]=DateStruct.date;	
			Timer[3]=TimeStruct.hours;			


		
		
		for(int i=0;i<sizeof(Timer)/sizeof(Timer[0]);i++)
		{
			sprintf(data_char+i*2,"%02d",Timer[i]);
		}
		printf("%s\r\n",data_char);

		mcu_dp_string_update(DPID_DRINK_TIME,(uint8_t *)data_char,sizeof(data_char)); //STRING型数据上报;
}






